package com.ruyuan.engine.utils;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisUtils {

    private static String IP;
    private static int PORT;
    //向redis要连接池的超时时间
    private static int timeout = 10000;
    private static JedisPool pool = null;
    static {
        Config load = ConfigFactory.load();
        IP = load.getString(Configuration.REDIS_HOST);
        PORT = Integer.parseInt(load.getString(Configuration.REDIS_PORT));
        JedisPoolConfig config = new JedisPoolConfig();
        //最大连接数，默认是1万
        config.setMaxTotal(1024);
        //最大空闲实例数
        config.setMaxIdle(200);
        //等连接池给连接的最大时间，毫秒，设成-1表示永远不超时
        config.setMaxWaitMillis(10000);
        //borrow一个实例的时候，是否提前进行validate操作
        config.setTestOnBorrow(true);
        pool = new JedisPool(config, IP, PORT, timeout);
    }

    public synchronized static Jedis getJedis() {
        if (pool != null) {
            return pool.getResource();
        } else {
            return null;
        }
    }

    public static void close(final Jedis redis) {
        if (redis != null) {
            redis.close();
        }
    }
}
